package cn.itcast.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author:王亚栋
 * @Date: 2023/7/3 下午9:21
 * @Version:1.0
 * 限流规则配置类
 */
@Configuration
@Slf4j(topic = "GatewayConfiguration")
public class GatewayConfiguration {

    private final List<ViewResolver> viewResolvers;

    private final ServerCodecConfigurer serverCodecConfigurer;

    /**
     * 构造器
     * @param viewResolversProvider
     * @param serverCodecConfigurer
     */
    public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                ServerCodecConfigurer serverCodecConfigurer){

        log.info("GatewayConfiguration 构造器...");

        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;

    }

    /**
     * 限流异常处理器
     * @return
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler(){

        log.info("限流异常处理器 ...");

        return new SentinelGatewayBlockExceptionHandler(viewResolvers,serverCodecConfigurer);

    }

    /**
     * 限流过滤器
     * @return
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public GlobalFilter sentinelGatewayFilter(){

        log.info("限流过滤器 ...");

        return new SentinelGatewayFilter();
    }

    /**
     * Spring 容器初始化的时候执行该方法
     */
    @PostConstruct
    public void doInit(){

        log.info("加载网关限流规则 ...");

        //加载网关限流规则
        initGatewayRules();
    }

    /**
     * 网关限流规则
     */
    private void initGatewayRules() {

        log.info("网关限流规则 ...");

        Set<GatewayFlowRule> rules = new HashSet<>();

        /**
         * resource: 资源名称，可以是网关中的route名称或用户自定义API分组名称
         * count:限流阈值
         * intervalSec:统计时间窗口，单位是秒，默认是1秒
         */
        rules.add(new GatewayFlowRule("order-service")
                .setCount(3)  //限流阈值
                .setIntervalSec(60)); //统计时间窗口，单位是秒，默认1秒

        rules.add(new GatewayFlowRule("user-service")
                .setCount(2)  //限流阈值
                .setIntervalSec(60)); //统计时间窗口，单位是秒，默认1秒

        //加载网关限流规则
        GatewayRuleManager.loadRules(rules);

    }
}
